import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/** @name 媒体数据分析平台状态管理 */
export const useMediaStore = defineStore('media', () => {
  // 采集相关状态
  const collectionHistory = ref(JSON.parse(localStorage.getItem('media_collection_history') || '[]'))
  const collectionProgress = ref({
    isCollecting: false,
    progress: 0,
    total: 0,
    current: 0,
    status: 'idle' // idle, collecting, completed, error
  })
  
  // 搜索相关状态
  const searchHistory = ref(JSON.parse(localStorage.getItem('media_search_history') || '[]'))
  const searchProgress = ref({
    isSearching: false,
    progress: 0,
    total: 0,
    current: 0,
    status: 'idle'
  })
  
  // 作品数据
  const works = ref([])
  const currentWork = ref(null)
  
  // 筛选条件
  const filterConditions = ref({
    contentType: ['video', 'image'],
    likesRange: [0, 999999],
    commentsRange: [0, 999999],
    dateRange: [],
    keywords: ''
  })
  
  // 计算属性
  const totalWorks = computed(() => works.value.length)
  const videoWorks = computed(() => works.value.filter(work => work.type === 'video'))
  const imageWorks = computed(() => works.value.filter(work => work.type === 'image'))
  const totalLikes = computed(() => works.value.reduce((sum, work) => sum + work.likes, 0))
  const totalComments = computed(() => works.value.reduce((sum, work) => sum + work.comments, 0))
  
  // Actions
  
  /** @name 添加采集历史记录 */
  function addCollectionHistory(record) {
    const historyRecord = {
      id: Date.now(),
      url: record.url,
      type: record.type,
      quantity: record.quantity || 1,
      includeComments: record.includeComments || false,
      includeUserInfo: record.includeUserInfo || false,
      timestamp: new Date().toISOString(),
      status: 'completed'
    }
    
    collectionHistory.value.unshift(historyRecord)
    
    // 保持最多50条记录
    if (collectionHistory.value.length > 50) {
      collectionHistory.value = collectionHistory.value.slice(0, 50)
    }
    
    // 保存到本地存储
    localStorage.setItem('media_collection_history', JSON.stringify(collectionHistory.value))
  }
  
  /** @name 更新采集进度 */
  function updateCollectionProgress(progress) {
    collectionProgress.value = { ...collectionProgress.value, ...progress }
  }
  
  /** @name 开始采集 */
  function startCollection(total = 1) {
    updateCollectionProgress({
      isCollecting: true,
      progress: 0,
      total,
      current: 0,
      status: 'collecting'
    })
  }
  
  /** @name 完成采集 */
  function completeCollection() {
    updateCollectionProgress({
      isCollecting: false,
      progress: 100,
      status: 'completed'
    })
  }
  
  /** @name 添加搜索历史记录 */
  function addSearchHistory(record) {
    const historyRecord = {
      id: Date.now(),
      keywords: record.keywords,
      filters: { ...record.filters },
      resultCount: record.resultCount || 0,
      timestamp: new Date().toISOString()
    }
    
    searchHistory.value.unshift(historyRecord)
    
    // 保持最多30条记录
    if (searchHistory.value.length > 30) {
      searchHistory.value = searchHistory.value.slice(0, 30)
    }
    
    // 保存到本地存储
    localStorage.setItem('media_search_history', JSON.stringify(searchHistory.value))
  }
  
  /** @name 更新搜索进度 */
  function updateSearchProgress(progress) {
    searchProgress.value = { ...searchProgress.value, ...progress }
  }
  
  /** @name 开始搜索 */
  function startSearch(total = 100) {
    updateSearchProgress({
      isSearching: true,
      progress: 0,
      total,
      current: 0,
      status: 'searching'
    })
  }
  
  /** @name 完成搜索 */
  function completeSearch() {
    updateSearchProgress({
      isSearching: false,
      progress: 100,
      status: 'completed'
    })
  }
  
  /** @name 设置作品数据 */
  function setWorks(newWorks) {
    works.value = newWorks
  }
  
  /** @name 添加作品 */
  function addWorks(newWorks) {
    works.value.push(...newWorks)
  }
  
  /** @name 清空作品数据 */
  function clearWorks() {
    works.value = []
  }
  
  /** @name 设置当前作品 */
  function setCurrentWork(work) {
    currentWork.value = work
  }
  
  /** @name 更新筛选条件 */
  function updateFilterConditions(conditions) {
    filterConditions.value = { ...filterConditions.value, ...conditions }
  }
  
  /** @name 重置筛选条件 */
  function resetFilterConditions() {
    filterConditions.value = {
      contentType: ['video', 'image'],
      likesRange: [0, 999999],
      commentsRange: [0, 999999],
      dateRange: [],
      keywords: ''
    }
  }
  
  /** @name 清空采集历史 */
  function clearCollectionHistory() {
    collectionHistory.value = []
    localStorage.removeItem('media_collection_history')
  }
  
  /** @name 清空搜索历史 */
  function clearSearchHistory() {
    searchHistory.value = []
    localStorage.removeItem('media_search_history')
  }
  
  return {
    // State
    collectionHistory,
    collectionProgress,
    searchHistory,
    searchProgress,
    works,
    currentWork,
    filterConditions,
    
    // Getters
    totalWorks,
    videoWorks,
    imageWorks,
    totalLikes,
    totalComments,
    
    // Actions
    addCollectionHistory,
    updateCollectionProgress,
    startCollection,
    completeCollection,
    addSearchHistory,
    updateSearchProgress,
    startSearch,
    completeSearch,
    setWorks,
    addWorks,
    clearWorks,
    setCurrentWork,
    updateFilterConditions,
    resetFilterConditions,
    clearCollectionHistory,
    clearSearchHistory
  }
})